% 载入数据
[X, Y] = iris_dataset();
[value, index] = max(Y);
y = index;

% 拉普拉斯平滑常数
smooth = 1e-9;

% 遍历标签, 计算 P(y=c_k)
uy = unique(y);
for k = 1: length(uy)
    py(k) = sum(y == uy(k)) / length(y);
end

% ### 求后验概率 ###
prop = [];
% 遍历每组数据
for k = 1: size(X, 2)
    col = X(:, k);
    % 遍历标签
    for m = 1: length(uy)
        pro = 1;
        % 遍历元素
        for l = 1: length(col)
            % 根据大数定律得出概率
            n = sum(X(l, :) == col(l) & (y == uy(m)));
            % 拉普拉斯平滑累乘
            pro = pro * py(m) * ((n + smooth) / (sum(y) + smooth));
        end
        % 保存对于每一个标签的后验概率
        prop(k, m) = pro;
    end
end

% 取每组中后验概率最大的标签所在的索引，作为预测分类
[value, haty] = max(prop, [], 2);
% 输出正确率
correct = sum(haty' == y);
disp(sprintf('correct: %d / %d', correct, length(y)));

% output: correct: 145 / 150